<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="餐食名称" prop="mealId">
        <el-select
          v-model="formData.mealId"
          clearable
          filterable
          placeholder="请选择"
          class="w-1/1"
          :filter-method="getRecipeMealList"
        >
          <el-option
            v-for="unit in RecipeMealList"
            :key="unit.id"
            :label="unit.mealName"
            :value="unit.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker
          v-model="formData.finishTime"
          type="date"
          value-format="x"
          placeholder="选择完成时间"
        />
      </el-form-item>
      <el-form-item label="告警状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择告警状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COOKED_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CookedApi, CookedVO } from '@/api/pm/cooked'
import { RecipeMealApi, RecipeMealVO } from '@/api/pplan/recipemeal'

/** 熟食成品管理 表单 */
defineOptions({ name: 'CookedForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 弹窗基础状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('') // create/update

// 表单数据
const formData = ref({
  id: undefined,
  mealId: undefined,
  mealName: undefined,
  finishTime: undefined,
  status: undefined
})

// 表单校验规则
const formRules = reactive({
  mealId: [{ required: true, message: '餐食id不能为空', trigger: 'change' }],
  finishTime: [{ required: true, message: '完成时间不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '告警状态不能为空', trigger: 'change' }]
})

const formRef = ref<any>(null) // 表单Ref

// -------------------------- 核心修改：解决餐食回显问题 --------------------------
// 1. 新增：存储完整的餐食列表（仅加载一次，避免重复请求）
const recipeMealAllList = ref<RecipeMealVO[]>([])
// 2. 新增：加载完整餐食列表的方法
const loadAllRecipeMeals = async () => {
  // 已加载过完整列表则直接返回，避免重复请求接口
  if (recipeMealAllList.value.length > 0) return recipeMealAllList.value
  const data = await RecipeMealApi.getRecipeMealSimpleList('')
  recipeMealAllList.value = data // 缓存完整餐食列表
  return data
}

// 3. 修改：餐食列表过滤方法（确保已选餐食在下拉列表中）
const RecipeMealList = ref<RecipeMealVO[]>([]) // 用于下拉显示的餐食列表
const getRecipeMealList = async (query?: string) => {
  // 确保先加载完整餐食列表
  await loadAllRecipeMeals()

  // 步骤1：提取表单中已选的餐食ID（单条选择，直接取mealId）
  const selectedMealId = formData.value.mealId
  const selectedMeals: RecipeMealVO[] = []
  // 若有已选ID，从完整列表中找到对应的餐食
  if (selectedMealId) {
    const selected = recipeMealAllList.value.find((item) => item.id === selectedMealId)
    if (selected) selectedMeals.push(selected)
  }

  // 步骤2：根据查询条件过滤显示列表（兼顾性能，无查询时只显示前200条）
  let filteredMeals: RecipeMealVO[] = []
  if (!query) {
    // 无查询时：取完整列表前200条
    filteredMeals = [...recipeMealAllList.value].slice(0, 200)
  } else {
    // 有查询时：按餐食名称模糊匹配
    filteredMeals = recipeMealAllList.value.filter((meal) =>
      meal.mealName.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 步骤3：合并“已选餐食”和“过滤结果”，并通过Map去重（避免重复选项）
  RecipeMealList.value = Array.from(
    new Map([...selectedMeals, ...filteredMeals].map((item) => [item.id, item])).values()
  )
  return RecipeMealList.value
}
// ------------------------------------------------------------------------------

/** 打开弹窗（修改：加载完整餐食列表并补全回显数据） */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 先加载完整餐食列表，再初始化显示列表
  await loadAllRecipeMeals()
  await getRecipeMealList('')

  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时加载熟食成品数据，并确保已选餐食在下拉列表中
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CookedApi.getCooked(id)
      // 重新触发过滤，补全已选餐食
      await getRecipeMealList('')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 暴露open方法供外部调用

/** 提交表单（原有逻辑未修改） */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as CookedVO
    if (formType.value === 'create') {
      await CookedApi.createCooked(data)
      message.success(t('common.createSuccess'))
    } else {
      await CookedApi.updateCooked(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单（原有逻辑未修改） */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mealId: undefined,
    mealName: undefined,
    finishTime: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}
</script>